package com.yitongmao.util;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Gson类库的封装工具类，专门负责解析json数据
 *
 * @author yfwang
 * @version 2.0
 */
public class JsonUtils {
    private static final Gson GSON = new Gson();

    private JsonUtils() {
    }

    public static final <T> T fromJson(String json, Type typeOfT) {
        return GSON.fromJson(json, typeOfT);
    }

    public static final <T> List<T> fromJson(String json) {
        Type type = new TypeToken<List<T>>() {
        }.getType();
        return GSON.fromJson(json, type);
    }

    public static final String toJson(Object o) {
        return GSON.toJson(o);
    }

    public static final String toJson(List<?> list) {
        Type type = new TypeToken<List<?>>() {
        }.getType();
        return GSON.toJson(list, type);
    }

    public static final Map<?, ?> toMap(String json) {
        Type type = new TypeToken<Map<?, ?>>() {
        }.getType();
        return GSON.fromJson(json, type);
    }

    public static final HashMap<String, String> toHashMap(String str) {
        HashMap<String, String> strMap = new HashMap<String, String>();
        // str==[{"type":"special","specialnodeid":"23747","specialnodepath":"图片"}]
        str = str.substring(str.indexOf("[") + 1, str.lastIndexOf("]"));
        str = str.substring(str.indexOf("{") + 1, str.lastIndexOf("}"));
        String[] strItem = str.split(",");
        for (int i = 0; i < strItem.length; i++) {
            String itemObj = strItem[i];
            String[] items = itemObj.split(":");
            items[0] = items[0].replace("\"", "");
            items[1] = items[1].replace("\"", "");
            strMap.put(items[0], items[1]);
        }
        return strMap;
    }

    public static final HashMap<String, String> json2Map(String str) {

        HashMap<String, String> result = new HashMap<String, String>();
        JSONObject jo = null;
        try {
            str = str.substring(1, str.length() - 1);

            jo = new JSONObject(str);
            for (Iterator iterator = jo.keys(); iterator.hasNext(); ) {
                String key = (String) iterator.next();
                String value = jo.get(key).toString();
                result.put(key, value);
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
        return result;
    }

}
